package com.ws.controller;

import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.ws.bean.Advertising;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.ws.bean.Log;
import com.ws.util.IPUtils;

@Controller
public class LogController {

    @SuppressWarnings("resource")
    @RequestMapping("/saveLog")
    @ResponseBody
    public String saveLog(HttpServletRequest request, HttpSession session, String event_type, String page) {
        /*
         * 获取操作日志信息，转换成json格式的数据
         */
        System.out.println("用户ID："+session.getId());
        System.out.println(event_type);
        System.out.println(page);
        String ip = IPUtils.getIpAddr(request);
        LocalDateTime datetime = LocalDateTime.now();
        String reqName = request.getRequestURI();
        StringBuffer reqURL = request.getRequestURL();
        Log log = new Log(session.getId(), event_type, page, ip, datetime, 0, reqName, reqURL);
        System.out.println(log);
        Object json = JSONObject.toJSON(log);
        System.out.println(json);

        String path = session.getServletContext().getRealPath("/logs/oa.log");
        System.out.println(path);
        /*
         *  把操作日志信息写入到日志文件中
         */
        try {
            FileWriter fw = new FileWriter(path, true);
            fw.write(json.toString());
            fw.write("\n");
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "true";
    }

    @RequestMapping("/sendBrowse")
    @ResponseBody
    public String sendBrowse(int aid, String atype, HttpSession session) {

        System.out.println(aid);
        System.out.println(atype);

        Advertising advertising = new Advertising(aid, atype, new Date(), 1, 1);
        Object json = JSONObject.toJSON(advertising);
        System.out.println(json);

        String realPath = session.getServletContext().getRealPath("/log/oa1.log");
//        FileUtils.writeStringToFile(json,  realPath);
        return "true";
    }
}
